package cn.ccenjie.wsy.controller;

import cn.ccenjie.wsy.config.SysConst;
import cn.ccenjie.wsy.vo.Resp;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.UUID;

@RestController
public class MessageController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/captcha.jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CaptchaUtil.out(new GifCaptcha(130, 48), request, response);
    }

    @PostMapping("/captcha_base64")
    @SuppressWarnings("unchecked")
    public Resp captcha() {
        GifCaptcha gifCaptcha = new GifCaptcha(130, 48);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(SysConst.CAPTCHA_PREFIX + uuid, gifCaptcha.text(), Duration.ofSeconds(60));
        return Resp.ok().data(new HashMap<String, Object>(){{put("id", uuid); put("data", gifCaptcha.toBase64());}});
    }
}
